package com.luca.sl651server.client.serial;

import com.luca.sl651server.client.serial.handler.SerialNettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.rxtx.RxtxChannel;
import io.netty.channel.rxtx.RxtxChannelConfig;
import io.netty.channel.rxtx.RxtxDeviceAddress;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class SerialNettyClient {

    private ChannelFuture channelFuture;
    private String portName;

    public SerialNettyClient(String portName) {
        this.portName = portName;
    }

    public void connect() {
        EventLoopGroup workerGroup = new OioEventLoopGroup();
        try {
            Bootstrap bootstrap  = new Bootstrap();
            bootstrap.group(workerGroup)
                    .channelFactory(() -> {
                        RxtxChannel rxtxChannel = new RxtxChannel();
                        rxtxChannel.config()
                                .setBaudrate(9600)
                                .setDatabits(RxtxChannelConfig.Databits.DATABITS_8)
                                .setParitybit(RxtxChannelConfig.Paritybit.NONE)
                                .setStopbits(RxtxChannelConfig.Stopbits.STOPBITS_1);
                        return rxtxChannel ;
                    })
                    .handler(new ChannelInitializer<RxtxChannel>() {
                        @Override
                        protected void initChannel(RxtxChannel rxtxChannel) {
                            rxtxChannel.pipeline().addLast(
                                    new LineBasedFrameDecoder(60000),
                                    new StringEncoder(StandardCharsets.UTF_8),
                                    new StringDecoder(StandardCharsets.UTF_8),
                                    new SerialNettyClientHandler()
                            );
                        }
                    });
            channelFuture = bootstrap.connect(new RxtxDeviceAddress(portName)).sync();
            if (channelFuture.isSuccess()) {
                log.info("Serial netty客户端连接服务端成功");
            }
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (workerGroup != null) {
                workerGroup.shutdownGracefully();
            }
        }
    }
}
